﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Solution.Application.Commands.Dtos;
using Solution.Application.Modules;

namespace Solution.Application.Commands.System.Authorize
{
    public class RequestHandler : IRequestHandler<Request, HandlerResult<string>>
    {
        private readonly JwtAuthentication _authentication;

        public RequestHandler(IOptions<JwtAuthentication> options)
        {
            _authentication = options.Value;
        }

        public async Task<HandlerResult<string>> Handle(Request request, CancellationToken cancellationToken)
        {
            if (request.Username == "admin" && request.Password == "admin")
            {
                return await Task.Run(() =>
                {
                    var claims = new[]
                    {
                        new Claim("username", request.Username),
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authentication.SecurityKey));
                    var token = new JwtSecurityToken(
                        issuer: _authentication.Issure, // 发布者
                        audience: _authentication.Audience, // 接收者
                        notBefore: DateTime.Now,    // token签发时间
                        claims: claims, // 该token内存储的自定义字段信息
                        expires: DateTime.Now.AddMinutes(_authentication.Expires),  // token过期时间
                        signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)  // 用于签发token的秘钥算法
                    );

                    return new HandlerResult<string>()
                    {
                        code = ResultCode.StatusOK,
                        msg = "",
                        data = $"{new JwtSecurityTokenHandler().WriteToken(token)}"
                    };
                });
            }
            return new HandlerResult<string>() { code = ResultCode.StatusOK, msg = "账号密码错误" };
        }
    }
}